#map_gen.py
import random, sys
import numpy as np
from time import time
from map_print import printer
from map_print2 import htmlprinter
import math

size = 801
ctime = str(int(time()))
rawmap = ctime+".pymap"
map = np.empty((size, size), object) #map will be accessed through map[i,j][z].  [z] is an array, use it's index for paramters.
borderlo = .05*size
borderhi = .95*size

def terrain(i,j):
	if (i<1 or j<1): #first line or first column
		x = random.randint(0, 30)
		#we want bias towards flat ground
		if x <=5 or x > 9:
			return 1#flat
		if x == 6:
			return 0#ravine
		if x == 7:
			return 2#hill
		if x == 8:
			return 3#mountain
		if x == 9:
			return 4#cliff
		else:
			print x
			return 1
	else:#available terrain data
		x = random.randint(0, 2)
		u = map[i-1,j][0]
		l = map[i,j-1][0]
		ul = map[i-1,j-1][0]
		if abs(u-l)==0:
			x = random.randint(u-1, u+1)
		elif(u>l and i<borderhi and i>borderlo and l>1):
			x = random.randint(u-1, u+1)
		elif(i>borderhi or i<borderlo):
			x = random.randint(l-1, l+1)
		else:
			x = random.randint(ul-1, ul+1)
		if(x<0):
			x=0
		elif(x>4):
			x=random.randint(3,4)
	return x

def water(i):
	r = random.random()
	if(i == -1, i == 0):
		if(r>0.3):
			return 1
	elif(i<4):
		if(r>0.159):
			return 1
	return 0

#necessary data for each grid
#terrain
#visibility to center
#water

def visible(i,j):
	mdpt = (size-1)/2
	diffi = mdpt - i
	diffj = mdpt - j
	tot = math.sqrt(i**2+j**2)
	startcell = (i,j)
	startht = map[i,j][0]
	curcell = (i,j)
	for i in range(int(tot)):
		if(map[curcell][0]>startht):
			return 0
		curcell = (curcell[0] - diffi/tot, curcell[1] - diffj/tot)
		if(curcell == (mdpt,mdpt)):
			return 1
	return 1
	

def simple_create():
	sz = size-1
	rm = open(rawmap, "a")
	for i in range(size):#row
		for j in range(size):#column
			map[i,j] = [0,0,0]
			a = terrain(i,j)
			map[i,j][0] = a
			if( i == (size-1)/2 and j == (size-1)/2): #this is the center
				map[i,j][0] = 5
	if(map[(size-1)/2,(size-1)/2][0] == 4):
		rm.close()
		print "center obstructed, starting over"
		rm = open(rawmap, "w")
		map.empty((size, size), object)
		simple_create()
	middle = range(sz/2-sz/10, sz/2+sz/10)
	
	for i in middle:#row
		for j in middle:#column
			map[i,j][2] = visible(i,j)
			map[i,j][1] = water(map[i,j][0])
			if( i == (size-1)/2 and j == (size-1)/2): #this is the center
				map[i,j][0] = 5
	#writing
	rm_cur_line = ""
	for i in range(size):#row
		for j in range(size):#column
			rm_cur_line = rm_cur_line + str(map[i,j][0]) + str(map[i,j][1]) + str(map[i,j][2])
		rm_cur_line = rm_cur_line + "\n"
		rm.write(rm_cur_line)
		rm_cur_line = ""
	rm.close()
simple_create()
#htmlprinter(map, ctime)
